<template>
  <div class="wages-set-group-add-wrapper page-miH page-bgBack">
    <a-row class="head">
      <div style="cursor: pointer" @click="handleCancel">
        <a-icon type="left" />
        <div class="left2">返回</div>
      </div>
      <a-col class="title">
        <strong>{{ isEdit ? "编辑薪资组" : "新增薪资组" }}</strong>
      </a-col>
    </a-row>
    <div class="set-add-wrapper">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <div class="form-title-wrapper">
          <span class="add-left-align" />
          <span style="color: rgba(0, 0, 0, 0.85)">基本设置</span>
        </div>
        <a-form-model-item label="薪资组名称" prop="name">
          <a-input v-model="form.name" placeholder="请输入" style="width: 225px" :disabled="form.name === '默认薪资组'" />
        </a-form-model-item>
        <a-form-model-item
          v-if="!form.isAllEmp"
          prop="empList"
          :rules="{
            required: true,
            message: '请选择'
          }"
          label="适用范围"
        >
          <div class="check-person-wrapper" @click="handleStaffVisible">
            <div class="out-person-wrapper">
              <span>共{{ form.empList.length }}人</span>
              <a-icon type="right" class="arrowIcon" />
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item v-if="form.isAllEmp" prop="empList" label="适用范围">
          <div style="font-weight: 600">全部员工</div>
        </a-form-model-item>
        <a-form-model-item label="适用模板" prop="salaryTemplateId">
          <a-select v-model="form.salaryTemplateId" style="width: 225px" placeholder="请选择">
            <a-select-option v-for="(item, index) in options" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <div class="form-title-wrapper">
          <span class="add-left-align" />
          <span style="color: rgba(0, 0, 0, 0.85)">设置计薪规则</span>
        </div>

        <a-form-model-item label="转正、调薪月规则" prop="changeSalaryRule">
          <a-select v-model="form.changeSalaryRule" style="width: 225px">
            <a-select-option :key="1" :value="1"> 按正式/调薪后的工资计算 </a-select-option>
            <a-select-option :key="2" :value="2"> 按试用期/调薪前的工资计算 </a-select-option>
            <a-select-option :key="3" :value="3"> 按转正/调薪前后的工资混合计算 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="计税规则" prop="taxId">
          <a-select v-model="form.taxId" style="width: 225px">
            <a-select-option :key="item.id" :value="item.id" v-for="item in optionsRule">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="应收服务费规则" prop="serviceFeeType">
          <a-select v-model="form.serviceFeeType" style="width: 225px">
            <a-select-option :key="1" :value="1"> 按人头收费 </a-select-option>
            <a-select-option :key="2" :value="2"> 按百分比收费 </a-select-option>
            <a-select-option :key="3" :value="3"> 一次性收费 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="应收服务费金额"
          prop="chargeAmount"
          v-if="form.serviceFeeType === 1 || form.serviceFeeType === 3"
          :rules="{
            required: true,
            message: '请输入'
          }"
        >
          <div>
            <a-input
              :min="0"
              :addonAfter="`${form.serviceFeeType === 3 ? '元' : '元/人'}`"
              v-model="form.chargeAmount"
              type="number"
              placeholder="请输入"
              style="width: 225px"
            />
          </div>
        </a-form-model-item>
        <a-form-model-item
          v-if="form.serviceFeeType === 2"
          prop="serviceFeeItem"
          :rules="{
            required: true,
            message: '请输入'
          }"
          label="收费百分比类型"
        >
          <a-select v-model="form.serviceFeeItem" style="width: 225px">
            <a-select-option key="人力成本" value="人力成本">人力成本</a-select-option>
            <a-select-option key="应发工资" value="应发工资">应发工资</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="form.serviceFeeType === 2"
          prop="proportion"
          :rules="{
            required: true,
            message: '请输入'
          }"
          label="收费百分比"
        >
          <a-input addon-after="%" :min="0" :max="100" v-model="form.proportion" type="number" style="width: 225px" />
        </a-form-model-item>
        <a-form-model-item
          v-if="form.serviceFeeType === 3"
          label="应收服务费月份"
          prop="billingMonth"
          :rules="{
            required: true,
            message: '请输入'
          }"
        >
          <a-month-picker v-model="form.billingMonth" format="YYYY-MM" placeholder="请选择" style="width: 225px" />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button @click="handleCancel"> 取消 </a-button>
          <a-button style="margin-left: 10px" type="primary" @click="saveGroup"> 确定 </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <employee-select
      :show.sync="isChooseStaff"
      :default-selected-keys="form.empList"
      :selected-list.sync="selectedList"
      @change="onEmployeeSelectChange"
    />

    <a-modal v-model="empConfirmVisible" title="人员确认" @ok="handleEmpConfirm">
      <div style="display: flex; justify-content: center">
        <div style="margin-right: 10px">
          <img :src="askImg" style="width: 30px" />
        </div>
        <div style="position: relative; top: 3px">{{ duplicateName }}已经在其他薪资组中，是否确认更换薪资组？</div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { getTemplates, getNotArchiveById, deleteSalaryGroupSalaries, batchDeleteSalaryGroupSalaries } from "@/api/wages/template";
import { addSalaryGroup, selectSalaryGroupEmp, getSalaryDetail, editSalaryGroup, findTaxRule } from "@/api/wages/set";
import Moment from "moment";
export default {
  components: {
    EmployeeSelect: () => import("@/components/EmployeeSelect2/employeeSelect-xinzi")
  },

  data() {
    return {
      showEmpList: false,
      size: null,
      originalSalaryTemplateId: "",
      groupId: "",
      duplicateName: "",
      selectedList: [],
      empConfirmVisible: false,
      isChooseStaff: false,
      isEdit: false,
      form: {
        empList: [],
        name: "",
        salaryTemplateId: undefined,
        taxId: undefined,
        changeSalaryRule: undefined,
        serviceFeeType: undefined,
        serviceFeeItem: undefined,
        billingMonth: null,
        chargeAmount: "",
        proportion: "",
        isAllEmp: false
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        isAllEmp: [{ required: true, message: "请选择", trigger: "change" }],
        salaryTemplateId: [{ required: true, message: "请选择", trigger: "change" }],
        changeSalaryRule: [{ required: true, message: "请选择", trigger: "change" }],
        taxId: [{ required: true, message: "请选择", trigger: "change" }],
        serviceFeeType: [{ required: true, message: "请选择", trigger: "change" }]
      },
      cacheEmpList: [],
      askImg: require("@/assets/img/wages/set/ask.png"),
      options: [],
      optionsRule: [],
      companyId: ""
    };
  },

  created() {
    this.companyId = this.$store.state.hr.companyId;
    this.init();
  },

  methods: {
    inputChange(e) {},
    keyPress(event) {
      var keyCode = event.keyCode;
      if (keyCode >= 48 && keyCode <= 57) {
        event.returnValue = true;
      } else {
        event.returnValue = false;
      }
    },
    handleSizeChange(e) {
      if (this.form.isAllEmp === true) {
        this.showEmpList = false;
      }
      if (this.form.isAllEmp === false) {
        this.showEmpList = true;
      }
    },
    init() {
      this.isEdit = Number(this.$route.query.isEdit) === 1;
      if (this.isEdit) {
        this.groupId = this.$route.query.groupId;
        getSalaryDetail(this.groupId)
          .then((res) => {
            this.form.name = res.data.name;
            this.selectedList = res.data.empInformationList;
            this.form.empList = res.data.empInformationList.map((item, index) => {
              return item.id;
            });

            this.form.salaryTemplateId = Number(JSON.parse(JSON.stringify(res.data.salaryTemplateId)));
            this.originalSalaryTemplateId = JSON.parse(JSON.stringify(res.data.salaryTemplateId));
            this.form.taxId = Number(res.data.taxId);
            this.form.changeSalaryRule = Number(res.data.changeSalaryRule);
            this.form.serviceFeeType = Number(res.data.serviceFeeType);
            this.form.serviceFeeItem = res.data.serviceFeeItem;
            this.form.billingMonth = res.data.billingMonth ? Moment(res.data.billingMonth) : null;
            this.form.chargeAmount = res.data.chargeAmount;
            this.form.proportion = res.data.proportion;
            this.form.isAllEmp = res.data.isAllEmp;
          })
          .catch((err) => {
            console.log("debug log --> ", err);
          });
      }
      const data = {
        companyId: this.companyId
      };
      getTemplates(data)
        .then((res) => {
          this.options = res.data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
      findTaxRule(this.companyId)
        .then((res) => {
          this.optionsRule = res.data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    handleStaffVisible() {
      this.isChooseStaff = true;
    },
    onEmployeeSelectChange(val) {
      const empList = val.map((item) => item.id);
      const data = {
        id: this.isEdit ? this.groupId : "",
        empList,
        companyId: this.companyId
      };
      selectSalaryGroupEmp(data)
        .then((res) => {
          if (res.data.length !== 0) {
            this.empConfirmVisible = true;
            this.duplicateName = res.data
              .map((item, index) => {
                return item.name;
              })
              .join(",");
            this.cacheEmpList = empList;
          } else {
            this.form.empList = empList;
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    handleEmpConfirm() {
      this.form.empList = this.cacheEmpList;
      this.empConfirmVisible = false;
    },
    saveGroup() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const data = {
            companyId: this.companyId,
            ...this.form
          };
          console.log(data);
          if (data.billingMonth) {
            try {
              data.billingMonth = this.form.billingMonth.format("YYYY-MM-DD");
            } catch (err) {
              console.log("xxx", err);
            }
          }
          if (this.isEdit) {
            if (this.originalSalaryTemplateId !== this.form.salaryTemplateId) {
              getNotArchiveById({
                salaryGroupId: this.groupId,
                salaryTemplateId: this.originalSalaryTemplateId
              }).then((res) => {
                if ((res.data && !res.data.length) || !res.data) {
                  data.id = this.groupId;
                  editSalaryGroup(data)
                    .then((res) => {
                      this.$router.push({
                        path: "/wages/set"
                      });
                      this.$message.success("薪资组编辑成功");
                    })
                    .catch((err) => {
                      console.log("debug log --> ", err);
                    });
                } else {
                  var idList = [];
                  res.data.forEach((item, index) => {
                    idList.push(item.id);
                  });
                  var arr = [];
                  res.data.forEach((item, index) => {
                    arr.push(item.monthly);
                  });
                  arr = arr.join(",");
                  const _this = this;
                  this.$confirm({
                    title: `该薪资组已在${arr}月创建月工资表，更换模板会同时删除未归档的月工资表中该薪资组的员工，仍旧继续吗？`,
                    onOk() {
                      batchDeleteSalaryGroupSalaries(idList).then(({ success }) => {
                        // deleteSalaryGroupSalaries(res.data.id).then(({ success }) => {
                        if (success) {
                          data.id = _this.groupId;
                          editSalaryGroup(data)
                            .then((res) => {
                              _this.$router.push({
                                path: "/wages/set"
                              });

                              _this.$message.success("薪资组编辑成功");
                            })
                            .catch((err) => {
                              console.log("debug log --> ", err);
                            });
                        }
                      });
                    }
                  });
                }
              });
            } else {
              data.id = this.groupId;
              editSalaryGroup(data)
                .then((res) => {
                  this.$router.push({
                    path: "/wages/set"
                  });
                  this.$message.success("薪资组编辑成功");
                })
                .catch((err) => {
                  console.log("debug log --> ", err);
                });
            }
          } else {
            addSalaryGroup(data)
              .then((res) => {
                this.$router.push({
                  path: "/wages/set"
                });
                this.$message.success("薪资组创建成功");
              })
              .catch((err) => {
                console.log("debug log --> ", err);
              });
          }
        }
      });
    },
    handleCancel() {
      const _this = this;
      this.$confirm({
        title: "薪资组内容未保存，是否确认离开？",
        okText: "确定",
        cancelText: "取消",
        onOk() {
          _this.$router.go(-1);
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.wages-set-group-add-wrapper {
  .head {
    .anticon-left {
      z-index: 3;
      left: 24px;
      position: absolute;
      color: #595959;
      font-size: 20px;
      margin-top: 21px;
    }
    .left2 {
      z-index: 3;
      left: 50px;
      position: absolute;
      color: #595959;
      font-size: 16px;
    }
    font-size: 16px;
    color: #000;
    font-weight: 500;
    text-align: center;
    line-height: 60px;
    height: 60px;
    border-bottom: 1px solid #e8e8e8;
  }
  .set-add-wrapper {
    padding: 24px;
  }
  .add-left-align {
    width: 3px;
    height: 20px;
    background: var(--primary);
    border-radius: 2px;
    display: inline-block;
    margin-right: 10px;
  }
  .form-title-wrapper {
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    padding-bottom: 15px;
    margin-bottom: 15px;
  }
  .check-person-wrapper {
    width: 100%;
    height: 35px;
    width: 225px;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    border: 1px solid rgba(236, 236, 236, 1);
    padding-left: 10px;
    cursor: pointer;
  }

  .out-person-wrapper {
    position: relative;
    bottom: 3px;
    display: flex;
    justify-content: space-between;
  }
  .arrowIcon {
    color: #d8d8d8;
    padding-right: 10px;
    padding-top: 12px;
  }
}
</style>
